<template>
  <div :id="id">
    <div id="main-video" class="video-item"></div>
  </div>
</template>
<script>
import GenerateTestUserSig from "./GenerateTestUserSig";
import TRTC from "trtc-js-sdk";
export default {
    props: {
        userId: String,
        roomId: String
    },
  data() {
    return {
      id: Math.random() + "",

      sdkAppId: "",
   
      userSig: "",
    
      client: "",
      members: new Map(),
      remoteStreams: [],
      isJoined: false,
      localStream: "",
    };
  },
  methods: {
    createClient() {
     
      var config = GenerateTestUserSig(this.userId);
      this.sdkAppId = config.sdkAppId;
      this.userSig = config.userSig;

      this.client = TRTC.createClient({
        mode: "rtc",
        sdkAppId: this.sdkAppId,
        userId: this.userId,
        userSig: this.userSig,
      });

      this.client.on("error", (err) => {
        console.error(err);
        alert(err);
        location.reload();
      });

      this.client.on("client-banned", (err) => {
        console.error("client has been banned for " + err);
      });

      // fired when a remote peer is joining the room
      this.client.on("peer-join", (evt) => {
        const userId = evt.userId;
        console.log("peer-join " + userId);
        // if (userId !== shareUserId) {
        //   // addMemberView(userId);
        // }
      });

      // fired when a remote peer is leaving the room
      this.client.on("peer-leave", (evt) => {
        const userId = evt.userId;
        console.log("peer-leave " + userId);
        // removeView(userId);
      });

      // fired when a remote stream is added
      this.client.on("stream-added", (evt) => {
        const remoteStream = evt.stream;
        const id = remoteStream.getId();
        const userId = remoteStream.getUserId();
        this.members.set(userId, remoteStream);
        console.log(
          `remote stream added: [${userId}] ID: ${id} type: ${remoteStream.getType()}`
        );
        // if (remoteStream.getUserId() === shareUserId) {
        //   // don't need screen shared by us
        //   this.client.unsubscribe(remoteStream);
        // } else {
        //   console.log("subscribe to this remote stream");
        //   this.client.subscribe(remoteStream);
        // }

        this.client.subscribe(remoteStream);
      });

      // fired when a remote stream has been subscribed
      this.client.on("stream-subscribed", (evt) => {
        const uid = evt.userId;
        const remoteStream = evt.stream;
        const id = remoteStream.getId();
        this.remoteStreams.push(remoteStream);
        remoteStream.on("player-state-changed", (event) => {
          console.log(`${event.type} player is ${event.state}`);
          if (event.type == "video" && event.state == "STOPPED") {
            // TODO
          }
          if (event.type == "video" && event.state == "PLAYING") {
            // TODO
          }
        });
        
        var div = document.createElement("div");
        div.classList.add("video-item");
        div.id = id
        document.getElementById(this.id).appendChild(div);

        remoteStream.play(id, { objectFit: "contain" });

        console.log("stream-subscribed ID: ", id);
      });

      // fired when the remote stream is removed, e.g. the remote user called Client.unpublish()
      this.client.on("stream-removed", (evt) => {
        const remoteStream = evt.stream;
        const id = remoteStream.getId();
        remoteStream.stop();
        this.remoteStreams = this.remoteStreams.filter((stream) => {
          return stream.getId() !== id;
        });

        console.log(
          `stream-removed ID: ${id}  type: ${remoteStream.getType()}`
        );
      });

      this.client.on("stream-updated", (evt) => {
        const remoteStream = evt.stream;
        let uid = this.getUidByStreamId(remoteStream.getId());
        // if (!remoteStream.hasVideo()) {
        //     $('#' + uid)
        //     .find('.member-video-btn')
        //     .attr('src', 'img/camera-off.png');
        // }
        console.log(
          "type: " +
            remoteStream.getType() +
            " stream-updated hasAudio: " +
            remoteStream.hasAudio() +
            " hasVideo: " +
            remoteStream.hasVideo() +
            " uid: " +
            uid
        );
      });
    },

    getUidByStreamId(streamId) {
      for (let [uid, stream] of this.members) {
        if (stream.getId() == streamId) {
          return uid;
        }
      }
    },

    async join() {
      if (this.isJoined) {
        console.warn("duplicate RtcClient.join() observed");
        return;
      }
      try {
        // join the room
        await this.client.join({
          roomId: this.roomId,
        });
        console.log("join room success");
        this.isJoined = true;

        this.localStream = TRTC.createStream({
          audio: true,
          video: true,
          userId: this.userId,
          mirror: true,
        });

        try {
          // initialize the local stream and the stream will be populated with audio/video
          await this.localStream.initialize();
          console.log("initialize local stream success");

          this.localStream.on("player-state-changed", (event) => {
            console.log(`local stream ${event.type} player is ${event.state}`);
          });

          // publish the local stream
          await this.publish();

          this.localStream.play("main-video");
        } catch (e) {
          console.error("failed to initialize local stream - " + e);
        }
      } catch (e) {
        console.error("join room failed! " + e);
      }
      //更新成员状态
      let states = this.client.getRemoteMutedState();
      for (let state of states) {
        console.log(state);
      }
    },

    async leave() {
      if (!this.isJoined) {
        console.warn("leave() - please join() firstly");
        return;
      }
      // ensure the local stream is unpublished before leaving.
      await this.unpublish();

      // leave the room
      await this.client.leave();

      this.localStream.stop();
      this.localStream.close();
      this.localStream = null;
      this.isJoined = false;
    },
    async publish() {
      if (!this.isJoined) {
        console.warn("publish() - please join() firstly");
        return;
      }
      if (this.isPublished) {
        console.warn("duplicate RtcClient.publish() observed");
        return;
      }
      try {
        await this.client.publish(this.localStream);
      } catch (e) {
        console.error("failed to publish local stream " + e);
        this.isPublished = false;
      }

      this.isPublished = true;
    },
    async unpublish() {
      if (!this.isJoined) {
        console.warn("unpublish() - please join() firstly");
        return;
      }
      if (!this.isPublished) {
        console.warn("RtcClient.unpublish() called but not published yet");
        return;
      }

      await this.client.unpublish(this.localStream_);
      this.isPublished = false;
    },

    muteLocalAudio() {
        this.localStream.muteAudio();
    },

    unmuteLocalAudio() {
        this.localStream.unmuteAudio();
    },

    muteLocalVideo() {
        this.localStream.muteVideo();
    },

    unmuteLocalVideo() {
        this.localStream.unmuteVideo();
    },

    resumeStreams() {
        this.localStream.resume();
        for (let stream of this.remoteStreams) {
            stream.resume();
        }
    }
  },
  mounted() {},
};
</script>
<style >
.video-item {
  width: 200px;
  height: 200px;
}
</style>